package org.lboot.flow.test.service;

import cn.hutool.core.thread.ThreadUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lboot.flow.FlowCtl;
import org.lboot.flow.event.FlowEventConsumer;
import org.lboot.flow.event.FlowEventConsumerMeta;
import org.lboot.flow.module.event.FlowCustomEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.util.Map;

@Slf4j
@Service
@AllArgsConstructor
public class FormCheckEventConsumer implements FlowEventConsumer {
    @Resource
    ApplicationContext context;
    @Override
    public String eventId() {
        return "form-check";
    }

    @Override
    public String consumerId() {
        return "test-consumer-1";
    }

    @Override
    public String consumerName() {
        return "表单校验实现1";
    }

    @Override
    public Map<String, Object> syncConsume(FlowCustomEvent event) {
        log.info("form-check 同步消费");
        return null;
    }

    @Override
    public void asyncConsume(FlowCustomEvent event) {
        ScriptEngineManager manager = new ScriptEngineManager();
        // 获取 JavaScript 的 ScriptEngine
        ScriptEngine engine = manager.getEngineByName("JavaScript");

        // 定义一个 JSON 字符串
        String json = "{\"name\":\"John\", \"age\":30}";

        // 将 JSON 字符串传递给脚本引擎
//        try {
//            // 解析 JSON 字符串为 JavaScript 对象
//            engine.eval("var obj = " + json + ";");
//            // 修改对象的属性
//            engine.eval("obj.name = 'Jane';");
//            engine.eval("obj.age = 25;");
//            // 添加一个新属性
//            engine.eval("obj.gender = 'female';");
//            // 将修改后的对象转换回 JSON 字符串
//            String modifiedJson = (String) engine.eval("JSON.stringify(obj);");
//            // 输出修改后的 JSON 字符串
//            System.out.println("Modified JSON: " + modifiedJson);
//        } catch (ScriptException e) {
//            e.printStackTrace();
//        }
        ThreadUtil.safeSleep(1000);
        log.info("form-check 异步消费");
    }


    @Override
    public FlowEventConsumerMeta meta() {
        return new FlowEventConsumerMeta();
    }
}
